package com.example.actflow.util;

import com.example.actflow.model.LogicItem;

import java.util.ArrayList;
import java.util.List;

public class LogicItemParser {

    public static LogicItem parse(String text) {
        String[] lines = text.split("\n");
        LogicItem root = null;
        List<LogicItem> currentPath = new ArrayList<>();

        for (String rawLine : lines) {
            if (rawLine.trim().isEmpty()) continue;

            int indent = countIndentLevel(rawLine);
            String line = rawLine.trim();

            LogicItem item = parseLine(line);
            if (item == null) continue;

            // 回退路径到正确层级
            while (currentPath.size() > indent) {
                currentPath.remove(currentPath.size() - 1);
            }

            if (!currentPath.isEmpty()) {
                currentPath.get(currentPath.size() - 1).children.add(item);
            } else {
                root = item; // 根节点
            }

            currentPath.add(item);
        }

        return root;
    }

    private static int countIndentLevel(String line) {
        int count = 0;
        for (char c : line.toCharArray()) {
            if (c == ' ') count++;
            else break;
        }
        return count / 4; // 每4个空格为1层
    }

    private static LogicItem parseLine(String line) {
        String[] split = line.trim().split("\\s+");

        if (split.length == 2 && split[0].equals("[条件]")) {
            return new LogicItem(LogicItem.Type.CONDITION, "根节点", null);
        }

        if (split[0].equals("[条件]")) {
            if (split.length != 4) {
                throw new RuntimeException("条件格式错误: " + line);
            }
            String target = split[1];
            String compareOp = split[2].split("\\(")[0];
            String param = split[2].split("\"")[1];
            String varName = split[3];
            return LogicItem.createCondition(target, compareOp, param, varName);
        }

        if (split[0].equals("[动作]")) {
            if (split.length != 4) {
                throw new RuntimeException("动作格式错误: " + line);
            }
            String target = split[1];
            String actionType = split[2];
            String delay = split[3].split("\"")[1];
            return LogicItem.createAction(target, actionType, Double.parseDouble(delay));
        }

        return null;
    }


}
